package com.zc.timedown.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zc.common.utils.DateUtils;
import com.zc.common.utils.UserThreadLocal;

import com.zc.timedown.domain.DailyQuote;
import com.zc.timedown.domain.DailyQuoteFavorite;
import com.zc.timedown.mapper.DailyQuoteFavoriteMapper;
import com.zc.timedown.mapper.DailyQuoteMapper;
import com.zc.timedown.service.ApiDailyQuoteService;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;

/**
 * 每日一句Service业务层处理
 *
 * @author zc
 * @date 2025-09-29
 */
@Service
public class ApiDailyQuoteServiceImpl extends ServiceImpl<DailyQuoteMapper, DailyQuote> implements ApiDailyQuoteService
{
    @Autowired
    private DailyQuoteMapper dailyQuoteMapper;

    @Autowired
    private DailyQuoteFavoriteMapper dailyQuoteFavoriteMapper;

    @Override
    public DailyQuote getDailyQuote(Long quoteId, Integer sourceType) {
        Long useId = UserThreadLocal.getUserId();
        DailyQuote dailyQuoteReq = new DailyQuote();
        dailyQuoteReq.setIsPublic(1);
        dailyQuoteReq.setIsSelfCreated(0);
        if (sourceType == 0){
            dailyQuoteReq.setPublishDate(LocalDate.now());
        }

       List<DailyQuote> dailyQuotes = dailyQuoteMapper.selectDailyQuoteList(dailyQuoteReq);
        if (dailyQuotes.size() <= 0){
            throw new RuntimeException("今日一句暂无数据");
        }
        int i = 0;
        DailyQuote dailyQuote = null;
        if(sourceType == 1 ){
            if (quoteId != null){
                Random random = new Random();
                int randomIndex = random.nextInt(dailyQuotes.size());
                dailyQuote = dailyQuotes.get(randomIndex);
            }else{
                dailyQuote = getRandomExcludingValue(dailyQuotes, quoteId);
            }

        }else {
            dailyQuote = dailyQuotes.get(i);
        }


        LambdaQueryWrapper<DailyQuoteFavorite> dailyQuoteFavoriteLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dailyQuoteFavoriteLambdaQueryWrapper.eq(DailyQuoteFavorite::getUserId,useId);
        List<DailyQuoteFavorite> dailyQuoteFavorites = dailyQuoteFavoriteMapper.selectList(dailyQuoteFavoriteLambdaQueryWrapper);
        List<Long> quoteIds = dailyQuoteFavorites.stream().map(DailyQuoteFavorite::getQuoteId).collect(Collectors.toList());

        // 设置收藏状态
        if (quoteIds.contains(dailyQuote.getId())){
            dailyQuote.setFavorite(true);
        }
        return dailyQuote;
    }

    /**
     * 从列表中随机获取一个不等于指定值的元素
     * @param list 数据列表
     * @param quoteId 要排除的值
     * @return 不等于排除值的随机元素，如果列表为空或所有元素都等于排除值则返回null
     */
    public DailyQuote getRandomExcludingValue(List<DailyQuote> list, Long quoteId) {
        if (list == null || list.isEmpty()) {
            return null;
        }

        Random random = new Random();
        DailyQuote selectedValue;
        int maxAttempts = list.size() * 10; // 防止无限循环
        int attempts = 0;

        do {
            int randomIndex = random.nextInt(list.size());
            selectedValue = list.get(randomIndex);
            attempts++;

            // 如果尝试次数过多，说明列表中可能都是要排除的值
            if (attempts > maxAttempts) {
                return null;
            }
        } while (selectedValue.getId().equals(quoteId));

        return selectedValue;
    }

    @Override
    public List<DailyQuote> getDailyQuoteList(Long useId) {
        DailyQuote dailyQuote = new DailyQuote();
        dailyQuote.setUserId(useId);
        List<DailyQuote> dailyQuotes = dailyQuoteMapper.selectDailyQuoteList(dailyQuote);
        return dailyQuotes;
    }

    @Override
    public Integer collectDailyQuote(Long useId, Long quoteId) {
        DailyQuote dailyQuote = dailyQuoteMapper.selectDailyQuoteById(quoteId);
        DailyQuoteFavorite dailyQuoteFavorite = new DailyQuoteFavorite();
        dailyQuoteFavorite.setUserId(useId);
        dailyQuoteFavorite.setQuoteId(dailyQuote.getId());
        dailyQuoteFavorite.setQuoteAuthor(dailyQuote.getAuthor());
        dailyQuoteFavorite.setQuoteContent(dailyQuote.getContent());
        dailyQuoteFavorite.setStatus(1);
        dailyQuoteFavorite.setCreateTime(LocalDateTime.now());
        int row = dailyQuoteFavoriteMapper.insert(dailyQuoteFavorite);
        return row;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Integer cancelCollectDailyQuote(Long useId, Long id) {
        int row = dailyQuoteFavoriteMapper.delete(new LambdaQueryWrapper<DailyQuoteFavorite>().eq(DailyQuoteFavorite::getUserId,useId).eq(DailyQuoteFavorite::getQuoteId,id));
        return row;
    }

    @Override
    public ArrayList<DailyQuoteFavorite> collectDailyQuoteFavoriteList(Long useId) {
        LambdaQueryWrapper<DailyQuoteFavorite> dailyQuoteFavoriteLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dailyQuoteFavoriteLambdaQueryWrapper.eq(DailyQuoteFavorite::getUserId,useId);
        List<DailyQuoteFavorite> dailyQuoteFavorites = dailyQuoteFavoriteMapper.selectList(dailyQuoteFavoriteLambdaQueryWrapper);
        return  new ArrayList<>(dailyQuoteFavorites);
    }

    @Override
    public List<DailyQuoteFavorite> getDailyCollectQuote() {
        Long userId = UserThreadLocal.getUserId();
        LambdaQueryWrapper<DailyQuoteFavorite> dailyQuoteFavoriteLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dailyQuoteFavoriteLambdaQueryWrapper.eq(DailyQuoteFavorite::getUserId,userId);
        List<DailyQuoteFavorite> dailyQuoteFavorites = dailyQuoteFavoriteMapper.selectList(dailyQuoteFavoriteLambdaQueryWrapper);
        return dailyQuoteFavorites;
    }

    /**
     * 新增每日一句
     *
     * @param dailyQuote 每日一句
     * @return 结果
     */
    @Override
    public int insertDailyQuote(DailyQuote dailyQuote)
    {

        dailyQuote.setCreateTime(DateUtils.getNowDate());
        return save(dailyQuote) == true? 1 : 0;
    }

    /**
     * 修改每日一句
     *
     * @param dailyQuote 每日一句
     * @return 结果
     */
    @Override
    public int updateDailyQuote(DailyQuote dailyQuote)
    {

        dailyQuote.setUpdateTime(DateUtils.getNowDate());
        return updateById(dailyQuote) == true ? 1 : 0;
    }


    /**
     * 删除每日一句信息
     *
     * @param id 每日一句主键
     * @return 结果
     */
    @Override
    public int deleteDailyQuoteById(Long id)
    {
        return removeById(id) == true ? 1 : 0;
    }

    @Override
    public int deleteDailyQuoteFavoriteById(Long id) {
        int row = dailyQuoteFavoriteMapper.deleteById(id);
        return row;
    }



}